/**
 * @FileName: Package.java
 * @Author
 * @Description:
 * @Date 2016年1月11日 下午4:32:49
 * @CopyRight ZTE Corporation
 */
package cn.hpclub.server.model;

import java.util.List;

import cn.hpclub.server.util.QueryHelper;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.Constant;
import cn.hpclub.server.util.InterfaceUtil;

@TableBind(tableName = "package")
public class Package extends Model<Package>{
    private static final long   serialVersionUID    = 1312507976941243069L;
    public static final Package dao                 = new Package();

    // 列名
    public final static String  TARIFF_CODE         = "tariff_code";
    public final static String  ID                  = "id";
    public final static String  NAME                = "name";
    public final static String  TYPE                = "type";
    public final static String  MONTHLY_CHARGE      = "monthly_charge";
    public final static String  PREDEPOSITED        = "predeposited";
    public final static String  DETAILS             = "details";
    public final static String  CREATED_TIME        = "created_time";
    public final static String  CREATED_BY          = "created_by";
    public final static String  ORG_ID              = "org_id";
    public final static String  SUMMARY             = "summary";
    public final static String  BRAND_ID            = "brand_id";
    public final static String  SORT            = "sort";
    public static final String  LAST_UPDATED_TIME   = "last_updated_time";
    public final static String  LOCALIZED       = "localized";

    public static final int     PG_TYPE_XHRW        = 1;                   // 选号入网：代表全号段选号入网和选号入网两种业务，包括普号、靓号、普号和靓号的数据
    public static final int     PG_TYPE_PH_YXHDXHRW = 2;                   // 营销活动选号入网

    public boolean update(String sql, Integer[] ids){
        int updateCount = Db.update(sql, (Object[])ids);
        if(updateCount > 0){
            return true;
        } else{
            return false;
        }
    }

    public boolean checkUnique(int id, String col, String value){
        try{
            List<Record> result = Db.find("select id from " + Constant.Table.PACKAGE + " where " + col + "=?"
                    + " and is_deleted=0 and enabled=1", new Object[] { value });
            if(result.size() <= 0 || result.get(0).getInt("id") == id){
                // System.out.println("checkUnique true col=" + col + ",value="
                // + value);
                return true;
            }

            // System.out.println("checkUnique false col=" + col + ",value=" +
            // value);
            return false;

        }
        catch(Exception e){
            e.printStackTrace();
            // System.out.println("checkUnique true col=" + col + ",value=" +
            // value);
            return true;
        }
    }

    public List<Record> getPackagesByType(int type, int orgId){
        String sqlExceptSelect = "";
        String orgSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in " + orgSql;
        }

        // 客户端传0（普号），则返回：0（普号）及2（普号和靓号）的套餐；客户端传1（靓号），则返回：1（靓号）及2（普号和靓号）的套餐；
        String sql = "select * from package where is_deleted=0 and enabled=1 and (type=? or type=2)" + sqlExceptSelect;
        return Db.find(sql, type);
    }

    public List<Record> getPackagesByTypeClient(int type, int orgId){
        // 客户端传2（营销活动选号入网），需要转成后台的3（营销活动选号入网），即，后台对应的是：0 表示普号， 1 表示靓号，2 普号和靓号，3
        // 营销活动选号入网
        if(type == 2)
            type = 3;
        String sqlExceptSelect = "";
        String sql = "";
        String orgSql = InterfaceUtil.getParentOrgIdSql(orgId, Constant.MAX_ORG_LEVEL);
        if(StrKit.notBlank(orgSql)){
            sqlExceptSelect += " and org_id in " + orgSql;
        }

        if(type == 3){
            // 客户端传2（营销活动选号入网），则返回：3（营销活动选号入网）的套餐；
            sql = "select * from package where is_deleted=0 and enabled=1 and type=?" + sqlExceptSelect;
        } else{
            // 客户端传0（普号），则返回：0（普号）及2（普号和靓号）的套餐；客户端传1（靓号），则返回：1（靓号）及2（普号和靓号）的套餐；
            sql = "select * from package where is_deleted=0 and enabled=1 and (type=? or type=2)" + sqlExceptSelect;
        }

        return Db.find(sql, type);
    }

    public Package getPackage(int packageId){
        String sql = "select * from package where id=? and enabled=1";

        return dao.findFirst(sql, packageId);

    }

    /**

     * 泛店员/普通店员：获取选号入网（代表全号段选号入网和选号入网两种业务）、营销活动选号入网可权限配置的套餐数据
     * 目前，以及远景，都希望泛店员和店员采用同一种逻辑。暂时，用相同逻辑。以后不同，则再进行分开。
     * 
     * @param pgType
     *            ： 类型：1-选号入网业务（包括普号、靓号、表示普号和靓号的数据）、2-营销活动选号入网业务（取营销活动选号入网类型数据）
     * 

     * @Title: getPackageList
     * @Description:条件：根据传入的是哪种业务类型，取相应类型的数据 + 只取自己创建的数据
     * @return List<Record>
     */
    public List<Record> getPackageList(int pgType){
        int orgId = InterfaceUtil.getOrgId();
        int orgTopId = InterfaceUtil.getIdTop();//省级，54470

        //省级和非省级的分开写，省级的无需关联localized_config表。地市，则需要。
        QueryHelper helper = null;
        if(orgId==orgTopId){
            helper = getListSqlForTopOrg(pgType, orgId);
        }else{
            helper = getListSqlForOthers(pgType, orgId, orgTopId);
        }

//        System.out.println("sql:"+helper.getSelect()+helper.getSqlExceptSelect());
        return Db.find(helper.getSelect()+helper.getSqlExceptSelect());

    }

    /**
     * 获取后台账号可以给APP配置的套餐列表，其他机构，如地市级，仅获取自己创建，或者省级创建并属地化给自己的套餐。
     * @param pgType
     * @param orgId
     * @param orgTopId
     * @return
     */
    private QueryHelper getListSqlForOthers(int pgType, int orgId, int orgTopId) {
        QueryHelper helper;
        helper = new QueryHelper("SELECT DISTINCT(pkg.id) as id, pkg.name as name ","package pkg LEFT JOIN localized_config lc ON ( lc.business =" +LocalizedConfig.TYPE_PACKAGE_XHRW+" AND lc.business_id = pkg.id )");
        helper.addCondition("pkg.is_deleted=0");
        helper.addCondition("pkg.enabled=1");

        helper.addCondition(PG_TYPE_XHRW == pgType,"(type=0 OR type=1 OR type=2)");
        helper.addCondition(PG_TYPE_PH_YXHDXHRW == pgType,"type=3");

        //对于地市级管理员，取自己创建的套餐（自己创建的套餐，无所谓属地化与否），或者省创建并属地化给自己的
        helper.addCondition("((pkg.org_id = ?) OR ( pkg.org_id = ? AND pkg.localized = ? AND lc.localized_city_id = ? ))",orgId,orgTopId, LocalizedConfig.LOCALIZED_LOCALIZED,orgId);
        return helper;
    }

    /**
     * @param pgType
     * @param orgId
     * @return
     *  省级账号，获取可配置的套餐列表：自己创建，并统一授权的有效套餐
     */
    private QueryHelper getListSqlForTopOrg(int pgType, int orgId) {
        QueryHelper helper = new QueryHelper("SELECT id,name","package");
        helper.addCondition("is_deleted=0");
        helper.addCondition("enabled=1");

        helper.addCondition(PG_TYPE_XHRW == pgType,"(type=0 OR type=1 OR type=2)");
        helper.addCondition(PG_TYPE_PH_YXHDXHRW == pgType,"type=3");

        //对于省级管理员，取自己的并且是统一授权的
        helper.addCondition("org_id=? AND localized=?",orgId, LocalizedConfig.LOCALIZED_UNIFIED);//省级：自己并且是统一授权的
        return helper;
    }

    /**
     * @Title: getSqlExceptSelect
     * @Description:泛店员获取已授权列表时组装sql脚本
     * @param pgType
     * @return String
     */
    public String getSqlExceptSelect(int pgType){
        String sql = "package bus_temp ON bac.config_business_id = bus_temp.id WHERE bus_temp.is_deleted = 0 AND bus_temp.enabled = 1";
        if(PG_TYPE_XHRW == pgType){
            sql += " AND (bus_temp.type=0 OR bus_temp.type=1 OR bus_temp.type=2)";
        } else if(PG_TYPE_PH_YXHDXHRW == pgType){
            sql += " AND bus_temp.type=3";
        }

        return sql;
    }
}
